import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import os
import csv

# ----------------------------
# 配置设备：CPU 或 GPU
# ----------------------------
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")

# ----------------------------
# 数据预处理 & 数据集
# ----------------------------
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))
])

train_dataset = datasets.MNIST(root='../data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='../data', train=False, download=True, transform=transform)

train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=1000, shuffle=False)

# ----------------------------
# 定义模型
# ----------------------------
class SimpleCNN(nn.Module):
    def __init__(self):
        super(SimpleCNN, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
        self.pool = nn.MaxPool2d(2, 2)
        self.fc1 = nn.Linear(64*14*14, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.relu(self.conv2(x))
        x = self.pool(x)
        x = x.view(x.size(0), -1)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = SimpleCNN().to(device)

# ----------------------------
# 损失函数和优化器
# ----------------------------
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# ----------------------------
# 保存模型和日志路径
# ----------------------------
save_dir = "../checkpoints"
os.makedirs(save_dir, exist_ok=True)
model_path_template = os.path.join(save_dir, "mnist_model_epoch_{:02d}.pth")
log_path = os.path.join(save_dir, "training_log.csv")

# ----------------------------
# 初始化 CSV 日志文件
# ----------------------------
with open(log_path, mode='w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(["epoch", "train_loss", "test_loss", "accuracy"])

# ----------------------------
# 训练函数
# ----------------------------
def train(epoch):
    model.train()
    running_loss = 0
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = criterion(output, target)
        loss.backward()
        optimizer.step()
        running_loss += loss.item()
        if batch_idx % 100 == 0:
            print(f"Train Epoch: {epoch} [{batch_idx*len(data)}/{len(train_loader.dataset)}]  Loss: {loss.item():.6f}")
    return running_loss / len(train_loader)

# ----------------------------
# 测试函数
# ----------------------------
def test():
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            test_loss += criterion(output, target).item()
            pred = output.argmax(dim=1)
            correct += pred.eq(target).sum().item()
    test_loss /= len(test_loader)
    accuracy = 100. * correct / len(test_loader.dataset)
    print(f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: {correct}/{len(test_loader.dataset)} ({accuracy:.2f}%)\n")
    return test_loss, accuracy

# ----------------------------
# 开始训练
# ----------------------------
num_epochs = 2
for epoch in range(1, num_epochs + 1):
    train_loss = train(epoch)
    test_loss, acc = test()

    # ----------------------------
    # 保存 PyTorch 模型权重
    # ----------------------------
    model_path = model_path_template.format(epoch)
    torch.save(model.state_dict(), model_path)
    print(f"Saved PyTorch model for epoch {epoch} at {model_path}")

    # ----------------------------
    # 导出 ONNX 模型
    # ----------------------------
    model.eval()  # 导出 ONNX 时必须切换到 eval 模式
    onnx_path = os.path.join(save_dir, f"mnist_model_epoch_{epoch:02d}.onnx")
    dummy_input = torch.randn(1, 1, 28, 28, device=device)

    torch.onnx.export(
        model,
        dummy_input,
        onnx_path,
        export_params=True,
        opset_version=17,
        do_constant_folding=True,
        input_names=['input'],
        output_names=['output'],
        dynamic_axes={'input': {0: 'batch_size'}, 'output': {0: 'batch_size'}}
    )
    print(f"Saved ONNX model for epoch {epoch} at {onnx_path}")

    # ----------------------------
    # 写入 CSV 日志
    # ----------------------------
    with open(log_path, mode='a', newline='') as f:
        writer = csv.writer(f)
        writer.writerow([epoch, train_loss, test_loss, acc])

print(f"All models and logs saved in {save_dir}")

# ----------------------------
# 加载任意保存的模型示例
# ----------------------------
# epoch_to_load = 3
# model.load_state_dict(torch.load(model_path_template.format(epoch_to_load)))
# model.to(device)
# test()
